package com.mingtu.jgspatrol.activity;

import android.os.Bundle;
import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.activity.NaviMapActivity;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.ConvertLatlng;
import com.mingtu.common.utils.GridSpacingItemDecoration;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.FireNoticePictureAdapter;
import com.mingtu.jgspatrol.base.MyBaseActivity;
import com.mingtu.jgspatrol.bean.FireNoticeDetailsBean;
import com.mingtu.jgspatrol.databinding.ActivityIndexFireDetails2Binding;
import com.mingtu.jgspatrol.utils.MyConstant;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class IndexFireDetails2Activity extends MyBaseActivity<ActivityIndexFireDetails2Binding> {
    private String fireId;
    private String lngStr;
    private String latStr;
    private List<FireNoticeDetailsBean.DataBean.FireInfoAttachEntityListBean> ReportDataBean = new ArrayList<>();
    private List<FireNoticeDetailsBean.DataBean.FireInfoAttachEntityListBean> SureDataBean = new ArrayList<>();

    private ArrayList<LocalMedia> selectPictureList1;
    private ArrayList<LocalMedia> selectPictureList2;

    private String createTime;
    private FireNoticePictureAdapter fireNoticePictureAdapter1;
    private FireNoticePictureAdapter fireNoticePictureAdapter2;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_index_fire_details2;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {
        GridLayoutManager layoutManager1 = new GridLayoutManager(context, 3);//第二个参数为网格的列数
        binding.reportPictureVideo.addItemDecoration(new GridSpacingItemDecoration(3, SizeUtils.dp2px(15), false));
        binding.reportPictureVideo.setLayoutManager(layoutManager1);

        fireNoticePictureAdapter1 = new FireNoticePictureAdapter(context, ReportDataBean);
        binding.reportPictureVideo.setAdapter(fireNoticePictureAdapter1);
        fireNoticePictureAdapter1.setOnItemClickListener(new FireNoticePictureAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                BaseApplication.initPreviewModel().startActivityPreview(position, false, selectPictureList1);
            }
        });

        GridLayoutManager layoutManager = new GridLayoutManager(context, 3);//第二个参数为网格的列数
        binding.surePictureVideo.addItemDecoration(new GridSpacingItemDecoration(3, SizeUtils.dp2px(15), false));
        binding.surePictureVideo.setLayoutManager(layoutManager);

        fireNoticePictureAdapter2 = new FireNoticePictureAdapter(context, SureDataBean);
        binding.surePictureVideo.setAdapter(fireNoticePictureAdapter2);
        fireNoticePictureAdapter2.setOnItemClickListener(new FireNoticePictureAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                BaseApplication.initPreviewModel().startActivityPreview(position, false, selectPictureList2);
            }
        });

        addClickListener(this, binding.ivFireLocation, binding.butSure);

    }

    @Override
    protected void getData() {
        fireId = getIntent().getStringExtra("fireId");
        String title = getIntent().getStringExtra("title");
        setModuleTitle(title);
        getFireNoticetDetails();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.iv_fire_location:
                bundle.putString("lng", lngStr);
                bundle.putString("lat", latStr);
                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), NaviMapActivity.class, bundle);
                break;
            case R.id.but_sure:
                sureEvent();
                break;
        }
    }

    /**
     * 火情详情
     */
    private void getFireNoticetDetails() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("fireId", fireId);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_FIRE_NOTICE_DETAILS + "/" + fireId)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                FireNoticeDetailsBean fireNoticeDetailsBean = new FireNoticeDetailsBean();
                                fireNoticeDetailsBean = gson.fromJson(result, FireNoticeDetailsBean.class);
                                FireNoticeDetailsBean.DataBean dataBean = fireNoticeDetailsBean.getData();
                                if (dataBean != null) {
                                    String uploadType = dataBean.getUploadType(); //预警方式
                                    //预警时间
                                    createTime = dataBean.getCreateTime();
                                    String address = dataBean.getAddress();
                                    String lnglat = dataBean.getLnglat();
                                    String gradeType = dataBean.getGradeType(); //火情等级
                                    String fireType = dataBean.getFireType(); //火情类型
                                    String resourceType = dataBean.getResourceType(); //资源类型
                                    String memo = dataBean.getMemo();
                                    String fireStatus = dataBean.getFireStatus(); //火情状态
                                    String confirmUserName = dataBean.getConfirmUserName();
                                    String confirmTime = dataBean.getConfirmTime();
                                    String finishTime = dataBean.getFinishTime();
                                    String status = dataBean.getStatus(); //0:待处理  1：处理中  2：已处理
                                    List<FireNoticeDetailsBean.DataBean.FireInfoAttachEntityListBean> listBeans = dataBean.getFireInfoAttachEntityList();

                                    if (!StringUtils.isEmpty(uploadType)) {
                                        binding.tvWarningType.setText(uploadType);
                                    }

                                    if (!StringUtils.isEmpty(createTime)) {
                                        binding.tvWarningTime.setText(createTime);
                                    }

                                    if (!StringUtils.isEmpty(address)) {
                                        binding.tvFireLocation.setText(address);
                                    }

                                    if (!StringUtils.isEmpty(lnglat)) {
                                        if (lnglat.indexOf(",") != -1) {
                                            String[] lnglatArray = lnglat.split(",");
                                            lngStr = lnglatArray[0];
                                            latStr = lnglatArray[1];
                                            double lat = Double.parseDouble(latStr);
                                            double lng = Double.parseDouble(lngStr);
                                            String myLng = ConvertLatlng.getInstance().convertToSexagesimal(lng);
                                            String myLat = ConvertLatlng.getInstance().convertToSexagesimal(lat);
                                            binding.tvFireLngLat.setText(myLng + "," + myLat);
                                        }
                                    }

                                    if (!StringUtils.isEmpty(confirmUserName)) {
                                        binding.tvConfirmPerson.setText(confirmUserName);
                                    }
                                    if (!StringUtils.isEmpty(confirmTime)) {
                                        binding.tvConfirmTime.setText(confirmTime);
                                    }
                                    if (!StringUtils.isEmpty(gradeType)) {
                                        binding.tvFireLevel.setText(gradeType);
                                    }
                                    if (!StringUtils.isEmpty(fireType)) {
                                        binding.tvFireType.setText(fireType);
                                    }
                                    if (!StringUtils.isEmpty(resourceType)) {
                                        binding.tvResourceType.setText(resourceType);
                                    }
                                    if (!StringUtils.isEmpty(fireStatus)) {
                                        binding.tvFireStatus.setText(fireStatus);
                                    }
                                    if (!StringUtils.isEmpty(memo)) {
                                        binding.tvFireMemo.setText(memo);
                                    }

                                    if (!StringUtils.isEmpty(finishTime)) {
                                        binding.tvFinishTime.setText(finishTime);
                                    }

                                    if (status.equals("1")) {
                                        binding.butSure.setVisibility(View.VISIBLE);
                                        binding.layoutFinish.setVisibility(View.GONE);
                                    } else {
                                        binding.butSure.setVisibility(View.GONE);
                                        binding.layoutFinish.setVisibility(View.VISIBLE);
                                    }


                                    if (listBeans != null) {
                                        if (listBeans.size() > 0) {
                                            ReportDataBean = new ArrayList<>();
                                            SureDataBean = new ArrayList<>();
                                            for (int i = 0; i < listBeans.size(); i++) { //将现场照片取出来
                                                String type = listBeans.get(i).getType();  //1:现场照片   2：确认照片
                                                if (type.equals("1")) {
                                                    ReportDataBean.add(listBeans.get(i));
                                                } else if (type.equals("2")) {
                                                    SureDataBean.add(listBeans.get(i));
                                                }
                                            }

                                            //现场照片逻辑
                                            if (ReportDataBean.size() > 0) {
                                                binding.reportPictureVideo.setVisibility(View.VISIBLE);
                                                selectPictureList1 = new ArrayList<>();
                                                lookPicVideoEvent(ReportDataBean, selectPictureList1, fireNoticePictureAdapter1);

                                            }

                                            /**
                                             * 确认照片逻辑
                                             */
                                            if (SureDataBean.size() > 0) {
                                                binding.surePictureVideo.setVisibility(View.VISIBLE);
                                                binding.layoutSurePic.setVisibility(View.VISIBLE);
                                                selectPictureList2 = new ArrayList<>();
                                                lookPicVideoEvent(SureDataBean, selectPictureList2, fireNoticePictureAdapter2);
                                            }
                                        }
                                    }

                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }


                        }
                    }
                });
    }

    /**
     * @param selectPictureList
     */
    private void lookPicVideoEvent(
            List<FireNoticeDetailsBean.DataBean.FireInfoAttachEntityListBean> DataBean,
            List<LocalMedia> selectPictureList,
            FireNoticePictureAdapter fireNoticePictureAdapter) {

        for (int i = 0; i < DataBean.size(); i++) {
            String url = DataBean.get(i).getUrl();
            String resType = "1";  //1:图片   3：视频
            boolean isHasVideo = PictureMimeType.isUrlHasVideo(url); //现在只有图片和视频，如果添加音频文件的话，此处逻辑要改
            if (isHasVideo) {
                resType = "3";
            }
            //设置资源类型，在adapter 中使用
            DataBean.get(i).setType(resType);
            LocalMedia localMedia = LocalMedia.generateHttpAsLocalMedia(url);
            selectPictureList.add(localMedia);
        }
        fireNoticePictureAdapter.upData(DataBean);
    }

    /**
     * 已经处理完成事件
     */
    private void sureEvent() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("fireId", fireId);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_FIRE_NOTICE_FINISH + "/" + fireId)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String success = jsonObject.getString("msg");
                            if (success.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("处理成功！");
                                //实例化Timer类 ,守护线程，不在后台一直运行
                                Timer timer = new Timer(true);
                                timer.schedule(new TimerTask() {
                                    public void run() {
                                        ActivityUtils.finishActivity(IndexFireDetails2Activity.class);
                                        EventBus.getDefault().post(new MyEventBus(MyConstant.REFRESH_FIRE_NOTICE_DATA));
                                    }
                                }, Constant.TIMER_TIME);

                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }
}